Ext.define('AlAjax', {

	statics : {

		postModel : function(url, record, callback, scope, body, eOpts) {
			eOpts = eOpts || {};
			eOpts.record = record;
			AlAjax.post(url, {jsonString : Ext.encode(record.data)}, callback, scope, body, eOpts);
		},

		postJsonString : function(url, jsonObject, callback, scope, body, eOpts) {
			eOpts = eOpts || {};
			eOpts.jsonObject = jsonObject;
			AlAjax.post(url, {jsonString : Ext.encode(jsonObject)}, callback, scope, body, eOpts);
		},

		post : function(url, params, callback, scope, body, eOpts) {
			AlUtil.wait(null,body);
			Ext.Ajax.request({
				url : url,
				params : params,
				success : function(response, options) {
					if (AlAjax.isSuccess(response)) {
						if (!Ext.isEmpty(callback)) {
							eOpts = eOpts || {};
							eOpts.body = body;
							callback.call(scope, response,options, eOpts);
						}
					}
				},
				failure : AlAjax.ajaxFailureHandler
			})
		},

		isSuccess : function(response) {
			AlUtil.resume();
			var rs = {};

			if (Ext.isEmpty(response.responseText)) return true;

			var text = response.responseText.trim();

			if (Ext.isEmpty(text)) return true;

			try {
				rs = Ext.decode(text);
			} catch (ex) {
				AlUtil.showMsg(_('json format is invalid!'), _('warning'), Ext.MessageBox.WARNING);
				return false;
			}
			if (Ext.isEmpty(rs.success) || rs.success) {
				return true;
			}

			if (Ext.isEmpty(rs.errDesc) && Ext.isEmpty(rs.msg)) {
				rs.errDesc =_('json data is invalid!');
			}
			if (!Ext.isEmpty(rs.msg)) {
				rs.errDesc = rs.msg;
			}
			AlUtil.showMsg(rs.errDesc, _('warning'), Ext.MessageBox.WARNING);
			return false;
		},
		responseHandler : function(response) {
			AlUtil.resume();
			var status = response.status;
			var text = response.responseText.trim();

			switch (status) {
				case 404 :
					AlUtil.showMsg(_("request url not found!"), _('warning'), Ext.MessageBox.WARNING);
					break;
				case 200 :
					return  AlAjax.isSuccess(response);
				case 0 :
					break;
				default :
					AlUtil.showMsg(status + "," + text,  _('warning'), Ext.MessageBox.WARNING);
					break;
			}
		},
		ajaxFailureHandler : function(response, options) {
			AlAjax.responseHandler(response);
		},
		ajaxRequestException : function( conn, response, options, eOpts )
		{
		    AlAjax.responseHandler(response);
		}
	}
});
